package com.avic.system.common.scheduled;


import com.avic.system.common.constant.CacheConstant;
import com.avic.system.common.constant.LocalCacheConstant;
import com.avic.system.dal.mapper.LoginLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 定时任务、整理地图应急数据：本地缓存数据、redis数据、数据库持久数据
 * @Author huangsheng
 * @Date 2018/9/29 20:20
 */
@Component
@Slf4j
public class SystemServiceScheduled {

    /**
     * 登入日志
     */
    @Autowired
    protected LoginLogMapper loginLogMapper;

    /**
     * redis客户端
     */
    @Autowired
    @Qualifier(CacheConstant.REDIS_BEAN_NAME)
    protected RedisTemplate redisTemplate;

    /**
     * 清理redis失效的单兵数据
     * 创建传输任务, 第一次延时1分钟, 1分钟扫描一次
     */
    @Scheduled(initialDelay = 1000 * 60, fixedRate = 1000 * 60 * 1)
    public void checkTokenUser() {
        log.info("执行token检查定时任务");
        Map<String, Integer> userIdMap = new HashMap(LocalCacheConstant.LOGIN_USER_ID.size());
        userIdMap.putAll(LocalCacheConstant.LOGIN_USER_ID);
        userIdMap.forEach((userId, userLoginId) -> {
            Object redisTokenObj = redisTemplate.opsForValue().get(CacheConstant.REDIS_MANAGEMENT_TOKEN_SPACE + userId);
            if (null == redisTokenObj) {
                if (userLoginId.equals(LocalCacheConstant.LOGIN_USER_ID.get(userId))) {
                    log.info("用户 {} token时效过期，退出登入", userId);
                    loginLogMapper.updateLoginDuration(userLoginId);
                    LocalCacheConstant.LOGIN_USER_ID.remove(userId);
                }
            }

        });

    }

}
